import React, { useEffect } from 'react';
import { notification, Button } from 'tdesign-react';
import { useNavigate } from 'react-router-dom';
import PubSub from 'pubsub-js';

const GlobalNotification: React.FC = () => {
  const navigate = useNavigate();

  useEffect(() => {
    // 订阅预约消息
    const reservationToken = PubSub.subscribe('reservationMessage', (_, data) => {
      if (data.type === 'reservation') {
        notification.info({
          title: '新的预约请求',
          content: (
            <div>
              <div>{data.message}</div>
              <div>预约时间：{new Date(data.data.startTime).toLocaleDateString()} - {new Date(data.data.endTime).toLocaleDateString()}</div>
              <div>预约用途：{data.data.purpose}</div>
            </div>
          ),
          footer: (
            <Button
              theme="primary"
              variant="text"
              onClick={() => {
                navigate(`/room/approve?id=${data.data.id}`);
              }}
            >
              去审批
            </Button>
          ),
          duration: 3000,
          closeBtn: true,
          icon: true,
        });
      }
    });

    // 订阅审批消息
    const approvalToken = PubSub.subscribe('approvalMessage', (_, data) => {
      let title = '';
      let content = '';
      let theme: 'success' | 'error' = 'success';

      if (data.type === 'approval') {
        if (data.data.status === 'approved') {
          title = '预约审批通过';
          content = `您的预约申请已通过审批\n`;
          theme = 'success';
        } else if (data.data.status === 'rejected') {
          title = '预约审批未通过';
          content = `您的预约申请未通过审批\n`;
          theme = 'error';
        }

        notification[theme]({
          title,
          content,
          duration: 3000,
          closeBtn: true,
          icon: true,
        });
      }
    });

    return () => {
      PubSub.unsubscribe(reservationToken);
      PubSub.unsubscribe(approvalToken);
    };
  }, [navigate]);

  return null; // 这个组件不需要渲染任何内容
};

export default GlobalNotification; 